package com.github.binarywang.demo.wechat.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestOperations;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.demo.wechat.config.WxCpProperties;
import com.github.binarywang.demo.wechat.repository.UserRepository;

@EnableConfigurationProperties(WxCpProperties.class)
@Service
public class LingLingServiceImpl implements LingLingService {
	public static final String REQUEST_PARAM = "requestParam";
	public static final String RESPONSE_RESULT = "responseResult";
	public static final String HEADER = "header";
	public static final String SIGNATURE = "signature";
	public static final String TOKEN = "token";

	public static final String HOST_SERVER = "http://llkmc.izhihuicheng.net:8889/cgi-bin/";
	public static final String HOST_OPEN_TOKEN = "7758D842D5A8622452FD635CE3964DED";// 填写您的openToken

	public static final String HOST_METHOD_ADD_DEVICE = "device/addDevice";// 添加设备
	public static final String HOST_METHOD_DEL_DEVICE = "device/delDevice";// 删除设备
	public static final String HOST_METHOD_UPDATE_DEVICE = "device/updateDevice";// 更新设备
	public static final String HOST_METHOD_GET_DEVICE_LIST = "device/queryDeviceList";// 查询设备列表
	public static final String HOST_METHOD_MAKE_SDK_KEY = "key/makeSdkKey";// 生成开门密钥
	public static final String HOST_METHOD_GET_LLID = "qrcode/getLingLingId";// 获取令令ID
	public static final String HOST_METHOD_GET_LLID_LIST = "qrcode/getLingLingIds";// 批量获取令令ID
	public static final String HOST_METHOD_ADD_OWNER_QRCODE = "qrcode/addOwnerQrCode";// 生成业主二维码
	public static final String HOST_METHOD_ADD_VISITOR_QRCODE = "qrcode/addVisitorQrCode";// 添加门禁访客二维码
	public static final String HOST_METHOD_DEL_VISITOR_QRCODE = "qrcode/delVisitorQrCode";// 删除访客二维码
	public static final String HOST_METHOD_GET_OPENDOORLOG = "openDoorLog/selectOpenDoorLog";// 日志查询

	@Autowired
	private RestOperations restOperations;
	@Autowired
	private WxCpProperties properties;
	@Autowired
	private UserRepository userRepository;

	/**
	 * POST请求
	 * 
	 * @param method
	 *            对应功能的url
	 * @param requestParam
	 *            请求的JSON格式参数
	 * @return 返回json数据
	 */
	private String doPost(String method, JSONObject requestParam) {
		String url = HOST_SERVER + method + "/" + HOST_OPEN_TOKEN;
		System.out.println("url --> " + url);
		JSONObject message = new JSONObject();
		message.put(REQUEST_PARAM, requestParam); // 原始请求参数
		// 生成消息头
		JSONObject header = new JSONObject();
		header.put(SIGNATURE, properties.getLingSignature());
		header.put(TOKEN, properties.getLingToken());
		message.put(HEADER, header);

		LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
		map.add("MESSAGE", message.toJSONString());
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		HttpEntity<LinkedMultiValueMap<String, String>> req = new HttpEntity<LinkedMultiValueMap<String, String>>(map,
				headers);
		JSONObject result = restOperations.postForEntity(url, req, JSONObject.class).getBody();
		System.out.println(result);
		return result.toString();

	}

	// 添加设备
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.github.binarywang.demo.wechat.service.LingLingService1#addDevice()
	 */
	@Override
	public void addDevice() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("deviceName", "设备名称");// 设备名称
		requestParam.put("deviceCode", "");// 设备的SN码
		String result = doPost(HOST_METHOD_ADD_DEVICE, requestParam);
		System.out.println("结果集 --> " + result);
	}

	// 删除设备
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.github.binarywang.demo.wechat.service.LingLingService1#delDevice()
	 */
	@Override
	public void delDevice() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("deviceId", 0);// 设备ID
		String result = doPost(HOST_METHOD_DEL_DEVICE, requestParam);
		System.out.println("结果集 --> " + result);
	}

	// 更新设备
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#updateDevice()
	 */
	@Override
	public void updateDevice() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("deviceId", 0);// 设备ID
		requestParam.put("newDeviceName", "linglingtest");// 新设备的名称（不填则不更改）
		// requestParam.put("newDeviceCode", "");// 新设备的SN码（不填则不更改，不建议修改SN码）
		String result = doPost(HOST_METHOD_UPDATE_DEVICE, requestParam);
		System.out.println("结果集 --> " + result);
	}

	// 查询设备列表
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#queryDeviceList()
	 */
	@Override
	public List queryDeviceList() {
		JSONObject requestParam = new JSONObject();
		String result = doPost(HOST_METHOD_GET_DEVICE_LIST, requestParam);
		System.out.println("结果集 --> " + result);
		return null;
	}

	// 生成开门密钥Key
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.github.binarywang.demo.wechat.service.LingLingService1#makeSdkKey()
	 */
	@Override
	public String makeSdkKey() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("deviceIds", new String[] { "" });// 设备ID数组
		requestParam.put("keyEffecDay", 180);// Key的有效天数（单位：天；最大值180天，不填默认180天，填超过180天取默认值）
		String result = doPost(HOST_METHOD_MAKE_SDK_KEY, requestParam);
		System.out.println("结果集 --> " + result);
		return null;
	}

	// 获取令令ID
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#getLingLingId()
	 */
	@Override
	public String getLingLingId() {
		JSONObject requestParam = new JSONObject();
		String result = doPost(HOST_METHOD_GET_LLID, requestParam);
		System.out.println("结果集 --> " + result);
		return null;
	}

	// 批量获取令令ID
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#getLingLingIds()
	 */
	@Override
	public List getLingLingIds() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("count", 10);// 批量生成令令ID的个数(输入的个数在1~20)
		String result = doPost(HOST_METHOD_GET_LLID_LIST, requestParam);
		System.out.println("结果集 --> " + result);
		return null;
	}

	// 生成业主二维码
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#addOwnerQrCode()
	 */
	@Override
	public void addOwnerQrCode() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("lingLingId", ""); // 令令ID
		requestParam.put("sdkKeys", new String[] { "" });// 控制设备的sdkKey
		requestParam.put("endTime", 4095); // 结果时间（单位：分钟；最大支持4095分钟）
		requestParam.put("effecNumber", 255);
		requestParam.put("strKey", "123456AA"); // 自定义密钥（二维码加密用的key，8位16进制的字符串）
		String result = doPost(HOST_METHOD_ADD_OWNER_QRCODE, requestParam);
		System.out.println("结果集 --> " + result);
	}

	// 添加门禁访客二维码
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#addVisitorQrCode()
	 */
	@Override
	public void addVisitorQrCode() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("lingLingId", "");// 令令ID
		requestParam.put("sdkKeys", new String[] { "" });// 控制设备的sdkKey
		requestParam.put("startTime", System.currentTimeMillis());// 开始时间（时间戳）
		requestParam.put("endTime", 4095);// 结果时间（单位：分钟；最大支持4095分钟）
		requestParam.put("effecNumber", 255);// 有效次数（取值0~255）
		requestParam.put("strKey", "123456AA");// 自定义密钥（二维码加密用的key，8位16进制的字符串）
		String result = doPost(HOST_METHOD_ADD_VISITOR_QRCODE, requestParam);
		System.out.println("结果集 --> " + result);

	}

	// 删除访客二维码
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#delVisitorQrCode()
	 */
	@Override
	public void delVisitorQrCode() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("codeId", 0);// 二维码ID
		String result = doPost(HOST_METHOD_DEL_VISITOR_QRCODE, requestParam);
		System.out.println("结果集 --> " + result);
	}

	// 日志查询
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.github.binarywang.demo.wechat.service.LingLingService1#selectOpenDoorLog(
	 * )
	 */
	@Override
	public void selectOpenDoorLog() {
		JSONObject requestParam = new JSONObject();
		requestParam.put("page", 1);// 分页的第几页（不填默认为1）
		requestParam.put("rows", 10);// 每页几行数据（不填默认为10）
		String result = doPost(HOST_METHOD_GET_OPENDOORLOG, requestParam);
		System.out.println("结果集 --> " + result);
	}

}
